class Work < ActiveRecord::Base
  belongs_to :ac_type
  has_many :results
  belongs_to :author
  has_many :flash_vars, :conditions => "space_type_id is not null"
  has_many :youku_and_tudou, :class_name => "FlashVar", :conditions => "space_type_id in (4,6)"
  validates_uniqueness_of :wid, :message => 'wid same'
  validates_presence_of :wid, :message => 'wid is null'
  validates_presence_of :cdate, :message => 'cdate is null'

  def get_info var=true, ac_type=true
    url = "http://#{BILI_PATH}/video/av#{wid}/"
    page = get_info_page url
    #name
    h2_title = page.search("h2[@id=titles]").first
    unless h2_title
      self.update_attribute(:status, 2) if page.search("script").to_s.include?("你输入的参数有误")
      return
    end
    self.name = h2_title.text
    #part_count
    select_option = page.search("select[@id=dedepagetitles]").first
    page_part_count = select_option ? select_option.search("option").size : 1
    self.part_count = page_part_count if self.part_count.to_i < page_part_count
    #danmu
    if var
      space_type, vid = Work.get_vid(page)
      flash_vars = FlashVar.all :conditions => ["work_id = ?", self.id]
      current_var = flash_vars.find{|flash_var| flash_var.vid == vid}
      if current_var
        current_var.update_attributes :vid => vid, :work_id => self.id, :space_type => space_type
      else
        FlashVar.create :vid => vid, :work_id => self.id, :space_type => space_type
      end
      if part_count > 1
        pages = []
        (2..part_count).each do |i|
          pages << get_info_page(url+"index_#{i}.html", i)
        end
        pages.each do |pa|
          space_type, vid = Work.get_vid(pa) 
          current_var = flash_vars.find{|flash_var| flash_var.vid == vid}
          if current_var
            current_var.update_attributes :vid => vid, :work_id => self.id, :space_type => space_type
          else
            FlashVar.create :vid => vid, :work_id => self.id, :space_type => space_type
          end
        end
      end
    end
    #type
    if ac_type
      tminfo = page.css("div.tminfo")
      type_name = tminfo.text.split('>')[2].delete!(' ')
      type_name = tminfo.text.split('>')[1].delete!(' ') if type_name.blank?
      t = AcType.find_by_name type_name
      self.ac_type_id = t.id if t
    end
    #author
    author_mid_script = page.search("script").detect{|sc| sc.get_attribute("src") && sc.get_attribute("src").split('&mid=').length > 1}
    author_mid = author_mid_script.get_attribute("src").split('&mid=').last
    usname = page.css("div.usname")
    login_name = nil
    nick_name = nil
    unless usname.empty?
      login_name =  usname.search("a").first.get_attribute("href").split('?uid=').last
      nick_name =  usname.text
    end
    author = Author.find_by_mid author_mid
    if author
      author.update_attribute :nick_name, nick_name if nick_name
    else
      author = Author.create! :login_name =>  login_name, :nick_name => nick_name, :mid => author_mid
    end
    self.author_id = author.id
    self.save!
  end

  def show_space_info ent=false
    if ent
      youku_and_tudou.collect{|fv| fv.space_type.name}.uniq.join('|')
    else
      flash_vars.collect{|fv| fv.space_type.name}.uniq.join('|')
    end
  end

  def get_info_page uri, i = 1, page = nil
      require 'net/http/persistent'
      @http ||= Net::HTTP::Persistent.new(nil, (PROXY ? URI.parse(PROXY) : nil))
      while true
        begin
          # 没有设置cookie的话这里将获取不到限制浏览的投稿的信息
          if COOK.blank?
            s = Timeout.timeout(10, ThreadError){@http.request(URI.parse(uri))}
          else
            s = Timeout.timeout(10, ThreadError){@http.request(URI.parse(uri), Net::HTTP::Get.new(uri, {'Cookie' => COOK}))}
          end
          page = Nokogiri::HTML(s.body.delete("\0"), nil, 'utf-8')
         break
        rescue
          p $!
        end
      end
      page
  end

  def self.get_vid page
    space_types = SpaceType.all
    ids = space_types.collect &:code
    embed = page.search("embed").first
    if embed
      vid_test = embed.get_attribute "flashvars"
      vid_ary = vid_test.split('&').collect{|pt| pt.split '='}.reverse.detect{|pt| ids.include?(pt.first)} rescue nil
      unless vid_ary.blank?
        vid = vid_ary[1]
        code = vid_ary[0]
      end
      unless vid
        src = URI.parse embed.get_attribute("src").delete(' ')
        vid_ary = src.query.split('&').collect{|pt| pt.split '='}.detect{|pt| ids.include? pt.first} rescue nil
        unless vid_ary.blank?
          vid = vid_ary[1]
          code = vid_ary[0]
        end
        p src unless vid
      end
    end
    space_type = SpaceType.find_by_code code
    return space_type, vid
  end
end
